package cn.shujuhai.qtadmin.platform.controller;

import java.util.ArrayList;

import org.jetbrains.annotations.NotNull;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.shujuhai.qtadmin.platform.domain.SysUser;
import cn.shujuhai.qtadmin.platform.domain.UserRole;
import cn.shujuhai.qtadmin.platform.pluging.logging.BusinessType;
import cn.shujuhai.qtadmin.platform.pluging.logging.Logging;
import cn.shujuhai.qtadmin.platform.pluging.result.Result;
import cn.shujuhai.qtadmin.platform.service.SysUserService;
import cn.shujuhai.qtadmin.platform.service.UserRoleService;

/**
 * 用户API
 *
 * @author dch798
 * @date 2021/08/21 22:13
 **/
@RestController
@RequestMapping("admin/user")
public class AdminUserController {

    public static final String EMAIL = "email";
    public static final String USER_ID = "user_id";
    final UserRoleService userRoleService;
    final SysUserService sysUserService;

    public AdminUserController(SysUserService sysUserService, UserRoleService userRoleService) {
        this.sysUserService = sysUserService;
        this.userRoleService = userRoleService;
    }

    /**
     *
     * @param page
     *            当前页
     * @return 用户列表
     */
    @PostMapping("userList")
    @Logging(title = "用户列表", describe = "用户列表", type = BusinessType.QUERY)
    public Result userList(Integer page, Integer limit, @NotNull SysUser userInfo) {
        PageMethod.startPage(page == 0 ? 1 : page, limit == 0 ? 15 : limit);
        var queryWrapper = new QueryWrapper<SysUser>();
        if (CharSequenceUtil.isNotBlank(userInfo.getEmail())) {
            queryWrapper.like(EMAIL, userInfo.getEmail());
        }
        if (CharSequenceUtil.isNotBlank(userInfo.getRealname())) {
            queryWrapper.like("name", userInfo.getRealname());
        }
        var userInfoList = userInfo.selectList(queryWrapper);
        return Result.success("获取成功", new PageInfo<>(userInfoList));
    }

    /**
     * 
     * @param id
     *            userid
     * @return result
     */
    @PostMapping("userDelete")
    @Transactional(rollbackFor = Exception.class)
    @Logging(title = "用户删除", describe = "用户删除", type = BusinessType.REMOVE)
    public Result userDelete(Long id) {
        this.sysUserService.removeById(id);
        this.userRoleService.remove(new QueryWrapper<UserRole>().eq(USER_ID, id));
        return Result.success("删除成功");
    }

    /**
     *
     * @param userInfo
     *            用户信息
     * @return 新增用户结果
     */
    @PostMapping("userAdd")
    @Transactional(rollbackFor = Exception.class)
    @Logging(title = "用户新增", describe = "用户新增", type = BusinessType.ADD)
    public Result userAdd(@NotNull SysUser userInfo) {
        if (userInfo.selectCount(new QueryWrapper<SysUser>().eq(EMAIL, userInfo.getEmail())) > 0) {
            return Result.failure("该账号已经注册");
        }
        userInfo.setPassword(new BCryptPasswordEncoder().encode(userInfo.getPassword()));
        if (userInfo.insert() && ObjectUtil.isNotEmpty(userInfo.getRoleIds())) {
            var userRoles = new ArrayList<UserRole>();
            for (Long roleId : userInfo.getRoleIds()) {
                var userRole = new UserRole();
                userRole.setUserId(userInfo.getId());
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
            this.userRoleService.saveBatch(userRoles);
        }
        return Result.success("新增成功", userInfo);
    }

    /**
     *
     * @param userInfo
     *            用户信息
     * @return 新增用户结果
     */
    @PostMapping("userUpdate")
    @Transactional(rollbackFor = Exception.class)
    @Logging(title = "用户修改", describe = "用户修改", type = BusinessType.EDIT)
    public Result userUpdate(@NotNull SysUser userInfo) {
        if (userInfo.updateById() && ObjectUtil.isNotEmpty(userInfo.getRoleIds())) {
            var userRoles = new ArrayList<UserRole>();
            for (Long roleId : userInfo.getRoleIds()) {
                var userRole = new UserRole();
                userRole.setUserId(userInfo.getId());
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
            this.userRoleService.remove(new QueryWrapper<UserRole>().eq(USER_ID, userInfo.getId()));
            this.userRoleService.saveBatch(userRoles);
        }
        return Result.success("修改成功");
    }
}
